package 剑指offer;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @description:
 * @author: ywk
 * @date: 2021-02-20
 */
public class 多个线程顺序打印ABC {
    static  AtomicBoolean flag = new AtomicBoolean();
    static String[] arr1 = {"A", "B", "C"};
    static int[] arr2 = {1, 2, 3};

    public static void main(String[] args) {

        StringBuffer sb = new StringBuffer();
        Thread thread1 = new Thread() {
            int count = 0;
            @Override
            public void run() {
                while (count < arr1.length) {
                    if (flag.get()) {
                        sb.append(arr1[count]);
                        count++;
                        flag.set(false);
                    }
                }
            }
        };


        Thread thread2 = new Thread() {
            int count = 0;
            @Override
            public void run() {
                while (count < arr2.length) {
                    if (!flag.get()) {
                        sb.append(arr2[count]);
                        count++;
                        flag.set(true);
                    }
                }
            }
        };

        thread1.start();
        thread2.start();
        try {
            Thread.currentThread().join(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(sb.toString());

    }

}
